//
//  ResetPwdViewController.m
//  WisdomFarm
//
//  Created by lijian on 2017/11/2.
//  Copyright © 2017年 sky. All rights reserved.
//

#import "ResetPwdViewController.h"
#import<CommonCrypto/CommonDigest.h>

@interface ResetPwdViewController ()

@end

@implementation ResetPwdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor grayColor];
    //顶部栏
    _myLabel=[[MyLabel alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 60)];
    _myLabel.textAlignment=UITextAlignmentCenter;
    _myLabel.textColor=[UIColor whiteColor];
    [_myLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]];
    _myLabel.backgroundColor=[UIColor colorWithRed:0 green:255 blue:255 alpha:10];
    _myLabel.text=@"修改密码";
    [_myLabel setVerticalAlignment:VerticalAlignmentBottom];
    [self.view addSubview:_myLabel];
    //返回按钮
    UIButton* btnBack=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    UIImage* img=[UIImage imageNamed:@"arrow.png"];
    [btnBack setBackgroundImage:img forState:UIControlStateNormal];
    btnBack.frame=CGRectMake(10, 25, 20, 30);
    [btnBack addTarget:self action:@selector(pressBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnBack];
    //[_myLabel addSubview:btnBack];
    //[_myLabel bringSubviewToFront:btnBack];
    
    NSArray* arrName=@[@"原密码",@"新密码",@"确认密码"];
    //内容部分
    for(int i=0;i<3;i++)
    {
        //底色
        UILabel* label=[[UILabel alloc]initWithFrame:CGRectMake(0, 60*(i+1), self.view.width, 60)];
        label.backgroundColor=[UIColor whiteColor];
        label.layer.borderColor=[[UIColor grayColor]CGColor];
        //[[UIColor colorWithRed:192 green:192 blue:192 alpha:10]CGColor];
        label.layer.borderWidth=0.5;
        [self.view addSubview:label];
        //名字
        UILabel* label1=[[UILabel alloc]initWithFrame:CGRectMake(0, 60*(i+1), 120, 60)];
        label1.text=[arrName objectAtIndex:i];
        label1.textAlignment=UITextAlignmentCenter;
        label1.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
        [self.view addSubview:label1];
        //输入框
        UITextField* tf=[[UITextField alloc]initWithFrame:CGRectMake(110, 70+60*i, 180, 40)];
        tf.placeholder=@"请输入密码";
        tf.secureTextEntry=YES;
        //设置文字
        //tf.text=@"Michael";
        tf.font=[UIFont systemFontOfSize:15];
        //tf.textColor=[UIColor blueColor];
        
        tf.borderStyle=UITextBorderStyleNone;
        tf.keyboardType=UIKeyboardTypeDefault;
        tf.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
        tf.tag=101+i;
        [_arrTextField addObject:tf];
        [self.view addSubview:tf];
        [self.view bringSubviewToFront:tf];
        //按钮
        UIButton* btn=[UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame=CGRectMake(self.view.width-45, 75+60*i, 45, 30);
        UIImage* imgeye=[UIImage imageNamed:@"eyeopen.png"];
        [btn setBackgroundImage:imgeye forState:UIControlStateNormal];
        btn.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin;
        btn.tag=104+i;
        [_arrBtn addObject:btn];
        [btn addTarget:self action:@selector(pressEye:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        
        //提交按钮
        //底色label
        UILabel* labelBtm=[[UILabel alloc]initWithFrame:CGRectMake(0, self.view.height-110, self.view.width, 60)];
        labelBtm.backgroundColor=[UIColor whiteColor];
        labelBtm.autoresizingMask=UIViewAutoresizingFlexibleTopMargin;
        [self.view addSubview:labelBtm];
        //[self.view bringSubviewToFront:labelBtm];
        
        UIButton* btnSubmit=[[UIButton alloc]initWithFrame:CGRectMake(10, self.view.height-100, self.view.width-20, 40)];
        btnSubmit.backgroundColor=[UIColor orangeColor];
        [btnSubmit setTitle:@"确认提交" forState:UIControlStateNormal];
        [btnSubmit setFont:[UIFont systemFontOfSize:18]];
        [btnSubmit addTarget:self action:@selector(pressSubmit) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btnSubmit];
        [self.view bringSubviewToFront:btnSubmit];
        
    }
    
    
    
}
//点击提交按钮
-(void) pressSubmit
{
  //todo
    UITextField* tfOrigin=[self.view viewWithTag:101];
    UITextField* tfNew=[self.view viewWithTag:102];
    UITextField* tfConfirm=[self.view viewWithTag:103];
    NSString* pwdOri=tfOrigin.text;
    NSString* pwdNew=tfNew.text;
    NSString* pwdConfirm=tfConfirm.text;
    
    
    
    if([pwdNew isEqualToString:pwdConfirm]==NO)
    {
        UIAlertView* alerView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"两次输入密码不一致，请重新输入！" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [alerView show];
    }else{
        if([pwdOri isEqualToString:pwdNew]==YES)
        {
            UIAlertView* alerView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"新密码与原密码相同，请重新输入！" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
            [alerView show];
        }
        else
        {
            //todo 调用接口判断并进行更新
            // 加密
            NSString* pwdOriMD5=[self md5:pwdOri];
            //[pwdOri MD5];
            NSLog(@"原始密码%@",pwdOriMD5);
            //
            NSString* pwdNewMD5=[self md5:pwdNew];
            //[pwdNew MD5];
            //
            NSString* mobi= WFStore.currentUser.phone;
            NSString* strUrl=[NSString stringWithFormat:@"http://122.224.174.181:8890/dataservice.asmx/ChangeUserFarmPassword?phone=%@&id=&oldpassword=%@&newpassword=%@",mobi,pwdOriMD5,pwdNewMD5];
            NSURL* url=[NSURL URLWithString:strUrl];
            NSURLRequest* request=[NSURLRequest requestWithURL:url];
            _connect=[NSURLConnection connectionWithRequest:request delegate:self];
            _data=[[NSMutableData alloc]init];
        }
    }
    
}

//点击明暗纹切换
-(void) pressEye:(UIButton*) btn
{
    [self resignFirstResponder
     ];
    btn.selected=!btn.selected;
    int tag=btn.tag;
    UITextField* tf=(UITextField*)[self.view viewWithTag:(tag-3)];
    NSString* str=tf.text;
    if(str.length>0){
        if(!btn.selected){
            UIImage* img=[UIImage imageNamed:@"eyeopen.png"];
            [btn setBackgroundImage:img forState:UIControlStateNormal];
            tf.secureTextEntry=YES;
        }else{
            UIImage* img=[UIImage imageNamed:@"eyeclosed.png"];
            [btn setBackgroundImage:img forState:UIControlStateNormal];
            tf.secureTextEntry=NO;
        }
    }else{
        btn.selected=!btn.selected;
    }
    [self becomeFirstResponder];
}
//返回上一页事件
-(void) pressBack{
    [self.navigationController popViewControllerAnimated:YES];
}

//md5加密
- (NSString *) md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return [output uppercaseString];
}
///NSUrlConnection代理协议实现
//1.网络连接错误时
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error=%@",error);
}
//2.处理服务器返回响应
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse* res=(NSHTTPURLResponse*)response;
    if(res.statusCode==200)
    {
        NSLog(@"服务器连接成功");
    }else if(res.statusCode==401)
    {
        UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"服务器无法连接，请稍后再试" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [alert show];
    }else if(res.statusCode==500)
    {
        UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"服务器无法连接，请稍后再试" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [alert show];
    }
}
//3.接受服务器数据调用
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}
//4.结束连接时调用
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
    NSString* code=[dic objectForKey:@"code"];
    NSString* msg=[dic objectForKey:@"msg"];
    UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alertView show];
}

-(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [(UITextField*)[self.view viewWithTag:101] resignFirstResponder];
    [(UITextField*)[self.view viewWithTag:102] resignFirstResponder];
    [(UITextField*)[self.view viewWithTag:103] resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
